class PowersController < ApplicationController
  # GET /powers
  # GET /powers.xml
  def index
    @powers = Power.find(:all)
    @chart_keys = get_breaker_keys
    @chart_data = get_24_hour_breaker_data
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @powers }
    end
  end

  # GET /powers/1
  # GET /powers/1.xml
  def show
    @power = Power.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @power }
    end
  end

  # GET /powers/new
  # GET /powers/new.xml
  def new
    @power = Power.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @power }
    end
  end

  # GET /powers/1/edit
  def edit
    @power = Power.find(params[:id])
  end

  # POST /powers
  # POST /powers.xml
  def create
    @power = Power.new(params[:power])

    respond_to do |format|
      if @power.save
        flash[:notice] = 'Power was successfully created.'
        format.html { redirect_to(@power) }
        format.xml  { render :xml => @power, :status => :created, :location => @power }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @power.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /powers/1
  # PUT /powers/1.xml
  def update
    @power = Power.find(params[:id])

    respond_to do |format|
      if @power.update_attributes(params[:power])
        flash[:notice] = 'Power was successfully updated.'
        format.html { redirect_to(@power) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @power.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /powers/1
  # DELETE /powers/1.xml
  def destroy
    @power = Power.find(params[:id])
    @power.destroy

    respond_to do |format|
      format.html { redirect_to(powers_url) }
      format.xml  { head :ok }
    end
  end

  def get_main_keys
    key_list = []
    keys = Power.find(:all, :select=> 'distinct key')
    keys.each do |key|
      if key.key != nil and key.key.index("CT") == nil
        key_list << key.key
      end
    end
    key_list
  end

  def get_breaker_keys
    key_list = []
    Power.find(:all, :select=> 'distinct key').each do |key|
      if key.key != nil and key.key.index("CT") != nil
      	 key_list << key.key
      end
    end
    key_list
  end

  def get_unique_keys
    key_list = []
    keys = Power.find(:all, :select => 'distinct key')
    keys.each do |key|
      if key.key != nil and key.key.index("CT") == nil
        key_list << IrisLookup.find(:first, :conditions=> {:address => key.key.split("-")[0], :key=>key.key.split("-")[1]}).description
      end
    end
    key_list
  end

  def get_data_points(first, last)
    Power.find(:all, :conditions=>["created_at > :start_time AND created_at < :end_time", {:start_time => first, :end_time => last}])
  end

  def get_24_hour_breaker_data
    keys = get_breaker_keys

    midnight = (Time.now - (Time.now.hour*60*60) - (Time.now.min*60) - (Time.now.sec)).localtime - 1.day
    points = get_data_points(midnight.gmtime, Time.now.gmtime)
    ltime = points[0].time - points[0].time.sec
    current_point = Hash.new

    data_points = []
    points.each do |point|
      time = point.time - point.time.sec
    if time == ltime or time == ltime + 1.minutes or time == ltime + 2.minutes
      current_point[point.key] = point.value
    else
      str_current_point = "['#{time.localtime.strftime("%A, %I:%M%p")}'"
      keys.each do |key|
        current_point[key] = 0 if current_point[key] == nil
        str_current_point += ",#{"%0.3f" % current_point[key]}"
      end
      str_current_point += "],"
      data_points << str_current_point  
        # reinitialize data for next point
        ltime = time
        # prev_point.destroy! - try if memory leak detected
        prev_point = current_point.clone
        current_point = Hash.new
        current_point[point.key] = point.value
      end
    end
    curr_time = Time.now + 15*60
    until curr_time > midnight + 1.day
      data_points << "['#{curr_time.strftime("%A, %I:%M%p")}',#{"0,"*keys.count}],"
      curr_time += 15*60
    end
    data_points
  end

  def get_24_hour_data
    # get index values
    #keys = Power.find(:all, :select => 'distinct key')
    keys = get_main_keys    

    # calculate the last midnight and translate it to gm time
    midnight = (Time.now - (Time.now.hour*60*60) - (Time.now.min*60) - (Time.now.sec)).localtime
    # get all points since midnight
    points = get_data_points(midnight.gmtime, Time.now.gmtime)
    # get the points for yesterday
    yday_points = get_data_points(1.day.until(midnight), midnight)
    
    ltime = points[0].time - points[0].time.sec
    current_point = Hash.new
    prev_point = Hash.new
    
    data_points = []
    points.each do |point|
      time = point.time - point.time.sec
      if time == ltime
        current_point[point.key] = point.value
      else
        prev_point = current_point.clone if prev_point.length == 0
        timescalar = ((time-ltime)/60.0/60.0)
        # construct a json data point string
        str_current_point = "['#{time.localtime.strftime("%A, %I:%M%p")}'"
        keys.each do |key|
          str_current_point += ",#{"%0.3f" % ((((current_point[key] - prev_point[key])/33.333)/timescalar)/1000.0)}"
        end
        str_current_point += "],"
        data_points << str_current_point
        
        # reinitialize data for next point
        ltime = time
        # prev_point.destroy! - try if memory leak detected
        prev_point = current_point.clone
        current_point = Hash.new
        current_point[point.key] = point.value
      end
    end
    curr_time = Time.now + 15*60
    until curr_time > midnight + 1.day
      data_points << "['#{curr_time.strftime("%A, %I:%M%p")}',0,0,0],"
      curr_time += 15*60
    end
    data_points
  end
end
